package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.swing.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 获得管理员权限授权token
 */
@Service
public class HuanXinTokenService {

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    //redis
    private RedisTemplate<String,String> redisTemplate;

    private  static  final ObjectMapper MAPPER = new ObjectMapper();

    private static final String tokenRedisKey = "HUANXIN_TOKEN";

    public  String getToken(){
        //先从redis中 查询
        String cacheData = this.redisTemplate.opsForValue().get(tokenRedisKey);
        if (StringUtils.isNotEmpty(cacheData)){
            return  cacheData;
        }
        //如果没有查询到 则请求  环信获取token
        //post http://a1.easemob.com/1122201027153967/tanhua/token
        String url = this.huanXinConfig.getUrl()
                +this.huanXinConfig.getOrgName()+"/"
                +this.huanXinConfig.getAppName()+"/token";

        //环信要求的 参数
        Map<String,Object> param = new HashMap<>();
        param.put("grant_type","client_credentials");
        param.put("client_id",this.huanXinConfig.getClientId());
        param.put("client_secret",this.huanXinConfig.getClientSecret());
        //往环信发送请求
        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, param, String.class);
        if(responseEntity.getStatusCodeValue()!=200){
            return null;
        }

        try {
            String body = responseEntity.getBody();
            JsonNode jsonNode = MAPPER.readTree(body);
            String accessToken = jsonNode.get("access_token").asText();
            //在环信失效前一天,提前失效
            long expiresIn = jsonNode.get("expires_in").asLong()-86400;
            //将token的值存储到redis中,并且添加过期时间
            this.redisTemplate.opsForValue().set(tokenRedisKey,accessToken,expiresIn, TimeUnit.SECONDS);

            //this.redisTemplate.opsForValue().set(tokenRedisKey, accessToken, 5, TimeUnit.DAYS);
            //直接设置有效期时间
            return accessToken;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return  null;
    }
}
